package com.hgsf.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 用于实体类继承重写toString()方法,自动生成json
 * @author 程顺鹏
 */
public class JsonTras {

	@Override
	public String toString(){

		Class<?> cls = this.getClass();
		StringBuffer buffer = new StringBuffer("{");
		try {
			// 不获取私有方法
			Method[] methods = cls.getMethods();
				// 得到所有field
				Field[] fields = cls.getDeclaredFields();
				for (Method method : methods) {
					String mn = method.getName();
					for (Field field : fields) {
						String name = field.getName().toString();
						if (mn.equalsIgnoreCase("get" + name)) {
							String value = (method.invoke(this) == null) ? "" : method.invoke(this).toString();
							buffer.append("\"" + name + "\"=\"" + value + "\",");
						}
					}
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
		buffer.delete(buffer.length() - 1, buffer.length());
		buffer.append("}");
		return buffer.toString();
	}
}